#include <iostream>

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include <QLabel>
#include <QDebug>

#include <opencv2/opencv.hpp>



extern "C"{
    #include <libavcodec/avcodec.h>
    #include <libavformat/avformat.h>
    #include <libavutil/avutil.h>
}


using namespace std;

class VideoPlayer : public QWidget {
    Q_OBJECT

public:
    VideoPlayer(QWidget *parent = nullptr) : QWidget(parent) {
        // 设置布局
        QVBoxLayout *layout = new QVBoxLayout(this);

        // 创建标签用于显示视频
        videoLabel = new QLabel("Video Stream", this);
        layout->addWidget(videoLabel);

        // 创建播放/暂停按钮
        QPushButton *playPauseButton = new QPushButton("Play/Pause", this);
        layout->addWidget(playPauseButton);
        connect(playPauseButton, &QPushButton::clicked, this, &VideoPlayer::togglePlayPause);

        // 创建关机按钮
        QPushButton *shutdownButton = new QPushButton("Shutdown", this);
        layout->addWidget(shutdownButton);
        connect(shutdownButton, &QPushButton::clicked, this, &VideoPlayer::shutdown);

        // 初始化视频捕获
        capture.open("rtsp://192.168.42.1/h264");
        if (!capture.isOpened()) {
            qDebug() << "Failed to open video stream";
            return;
        }

        // 设置定时器更新视频帧
        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &VideoPlayer::updateFrame);
        timer->start(40); // 30毫秒更新一次
    }

public slots:
    void updateFrame() {
        cv::Mat frame;
        if (isPlaying) {
            capture >> frame;
            if (!frame.empty()) {
                // 将OpenCV图像转换为Qt图像
                QImage qimg(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_BGR888);
                videoLabel->setPixmap(QPixmap::fromImage(qimg));
            }
        }
    }

    void togglePlayPause() {
        isPlaying = !isPlaying;
    }

    void shutdown() {
        capture.release();
        qApp->quit();
    }

private:
    QLabel *videoLabel;
    QTimer *timer;
    cv::VideoCapture capture;
    bool isPlaying = true;
};
#include "main.moc"
//主函数
int main(int argc, char *argv[]){
    cout << "qt_rtsp_show_ui ~~~\n";
    cout << "******************************************************\n";
    cout << "FFmpeg      version：" << av_version_info() << "\n";
    cout << "libavcodec  version：" << avcodec_version() << "\n";
    cout << "libavformat version：" << avformat_version() << "\n";
    cout << "libavutil   version：" << avutil_version() << "\n";
    cout << "******************************************************\n";

    QApplication app(argc, argv);
    VideoPlayer player;
    player.show();
    return app.exec();
}

